//index.js
import {
  timeFilter
} from '../../utils/util'
//获取应用实例
const app = getApp()

Page({
  data: {
    channel: '',
    activeTab: 0,
    user_id: '',
    show: false,
    userChannels: [],
    active: 0,
    channelId: "",
    showDeleteBtn: false,
    channels: []

  },
  // 跳转到搜索页
  toSearch: function () {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },
  // 跳转到文章页
  toArticle(e) {
    let aId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/article/article?id=' + aId
    })
  },
  showPopup() {
    // console.log(e);
    this.setData({
      show: true
    })
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  onShowDeleteBtn() {
    this.setData({
      showDeleteBtn: !this.data.showDeleteBtn
    })
  },
  showChannel() {
    wx.request({
      url: 'http://ttapi.research.itcast.cn/app/v1_0/user/channels',
      method: "GET",
      header: {
        "content-type": "application/json"
      },
      success: res => {
        // console.log(res);
        this.setData({
          userChannels: res.data.data.channels

        })
        // this.data.channelId = this.data.userChannels[this.data.active].id
        console.log(this.data.userChannels);
      },
      fail: err => {
        console.log(err);
      }
    }),
      wx.request({
        url: 'http://ttapi.research.itcast.cn/app/v1_0/channels',
        method: "GET",
        header: {
          "content-type": "application/json"
        },
        success: res => {
          console.log(res);
          this.setData({
            channels: res.data.data.channels
          })
          console.log(this.data.channels);
        },
        fail: err => {
          console.log(err);
        }
      })
  },
  // 添加channel
  // addUserChannel:data=>{
  //   // console.log(data)
  //   wx.request({
  //     url: 'http://ttapi.research.itcast.cn/app/v1_0/channels/' + data,
  //     method:"PATCH",
  //     header:{
  //       "content-type":"application/json"
  //     },
  //     success:res=>{
  //       console.log(res);
  //     },
  //     fail:err=>{
  //       console.log(err);
  //     }
  //   })
  // },
  // 删除channel
  deleteUserChannel: (channelId) => {
    wx.request({
      url: 'http://ttapi.research.itcast.cn/app/v1_0/user/channels/' + channelId,
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "Authorization": "Bearer " + wx.getStorageSync('token')
      },
      method: "delete",
      success: res => {
        // if(res.statusCode == 401)
        // return
        //   wx.showToast({
        //     title: '请先登录',
        //     icon:'danger'
        //   })
        
        console.log(res);
      },
      fail: err => {
        console.log(err);
       
      }
    })
  },
  onLoad() {
    this.data.user_id = wx.getStorageSync('user').id || ''
    // 当有token时
    if (wx.getStorageSync('token')) {
      this.getUserChannels()
      // 没有token也就是没有登录时
    } else {
      this.getChannels()
    }
    this.showChannel();
  },
  // 获取用户频道
  getUserChannels() {
    wx.request({
      url: 'http://ttapi.research.itcast.cn/app/v1_0/user/channels',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: function (res) {
        // 如果令牌出错
        if (res.statusCode == 401) {
          wx.clearStorageSync()
          this.getChannels()
          return
        }
        // 给每个频道添加一个空文章数组
        res.data.data.channels.forEach(item => {
          item.articles = []
          item.no_more = false
        })
        this.setData({
          channel: res.data.data.channels
        })
        // 获取第一个频道下的文章
        this.getAriticles(res.data.data.channels[0].id)
      }.bind(this)
    })
  },
  // 非登录时获取频道
  getChannels() {
    wx.request({
      url: 'http://ttapi.research.itcast.cn/app/v1_0/user/channels',
      success: function (res) {
        this.setData({
          channel: res.data.data.channels
        })
        // 给每个频道添加一个空文章数组
        res.data.data.channels.forEach(item => {
          item.articles = []
          item.no_more = false
        })
        // 获取第一个频道下的文章
        this.getAriticles(res.data.data.channels[0].id)
      }.bind(this)
    })
  },
  // tab切换时
  tabChange(e) {
    let thisId = this.data.channel[e.detail.index].id
    this.data.activeTab = thisId
    // 如果该频道已有文章，则不获取 返回false
    if (this.data.channel[e.detail.index].articles[0]) return false
    // 获取频道下的文章
    this.getAriticles(thisId)
  },
  // 获取频道下的文章
  getAriticles(theId) {
    // 获取时间戳
    let stamp = (new Date().getTime()).toString()

    wx.request({
      url: 'http://ttapi.research.itcast.cn/app/v1_1/articles',
      header: {
        "Authorization": "Bearer " + wx.getStorageSync('token')
      },
      data: {
        channel_id: theId,
        timestamp: stamp,
        with_top: 1
      },
      dataType: '其他',
      success: function (res) {
        console.log(this.data)
        let filterData = res.data.replace(/\"art\_id\"\:\s\d+/g, function (str) {
          return str.replace(/\d+/, function (str2) {
            return '"' + str2 + '"'
          })
        })
        res.data = JSON.parse(filterData)
        let theIndex = this.data.channel.findIndex(item => item.id == theId)
        // 当获取到零篇文章时，给文章的no_more设置为true
        if (!res.data.data.results[0]) {
          let changeStr = 'channel[' + theIndex + '].no_more'
          this.setData({
            [changeStr]: true
          })
          return
        }
        // 给目标id的频道的文章列表添加文章
        let changeStr = 'channel[' + theIndex + '].articles'
        this.data.channel[theIndex].articles = this.data.channel[theIndex].articles.concat(res.data.data.results)
        this.setData({
          [changeStr]: this.data.channel[theIndex].articles
        })
        // 当总文章数不足8个时，再加载获取
        if (this.data.channel[theIndex].length < 8) {
          this.getAriticles(theId)
        }
      }.bind(this)
    })
  },
  // 触底刷新
  onReachBottom(e) {
    this.getAriticles(this.data.activeTab)
  },
  onShow() {
    // 当用户发生改变时，重新刷新页面
    let new_user = wx.getStorageSync('user')
    if (new_user.id !== this.data.user_id) {
      this.onLoad()
      this.data.user_id = new_user.id
    }
  },
  // 添加我的频道
  onAllChannelClicked(e) {
    let index = e.currentTarget.dataset.index;

    if (this.data.userChannels.findIndex(v => { v.id == this.data.channels.id })) {
      let data = this.data.channels.splice(index, 1);
      this.data.userChannels.push(data[0]);
      // let params = {
      //   channels: [
      //     {
      //       id: data[0].id,
      //       seq: data[0].id
      //     }
      //   ]
      // };
      this.setData({
        userChannels: this.data.userChannels,
        channels: this.data.channels
      })
    }

    // console.log(this.data.userChannels);

    // this.addUserChannel(params)

  },
  onDeleteChannel(e) {
    let index = e.currentTarget.dataset.index;
    // console.log(index);
    let data = this.data.userChannels.splice(index, 1);
    this.data.channels.push(data[0]);
    this.deleteUserChannel(data[0].id);
    this.setData({
      userChannels: this.data.userChannels,
      channels: this.data.channels,
      channel: this.data.channel
    })

  },
})